<?php
#################
###Mysql class###
#################

// works fine
// TODO: script improuvments, as always...

###TEST SCRIPT HERE###
/*
include_once('../functions/security.php');
$db = new DbMysql();
$db->CreateTable('usser', array('logg' => ' varchar(25)'));
$db->AddLine('usser', array('id' => NULL, 'logg' => 'Meanor1'));
$db->AddLine('usser', array('id' => NULL, 'logg' => 'Meanor2'));
$db->AddLine('usser', array('id' => NULL, 'logg' => 'Meanor3'));
$db->AddLine('usser', array('id' => NULL, 'logg' => 'Meanor4'));
$meanor2 = $db->GetLine('usser', 'logg = \'Meanor4\'');
echo $meanor2['id'];
$db->Query('Select * from usser');
echo 'results found:'.$db->Query2Num().'<br />';
$db->UpdateData('usser', array('logg' => 'Meanor33'), 'logg = \'Meanor3\'');
foreach($db->Query2Array('id') as $column=>$value)
    echo $column.$value['logg'].'<br />';
echo 'Meanor2 exist:'.$db->IsExist('usser', 'logg = \'Meanor2\'');
*/
###End of test script###

###Header###

interface iDatabase
{
    // Connecting to the database, using preference's options
    public function __construct();
    // Set a char set
    public function SetCharset($charset);
    // Executing a query
    public function Query($query);
    // Query result to array
    public function Query2Array();
    // Counting result lines
    public function Query2Num();
    // Creating table
    public function CreateTable($tableName, $fields);
    // Deleting table
    public function DeleteTable($tableName);
    // Adding a line into a table
    public function AddLine($tableName, $fields);
    // Deleting data from a table
    public function DeleteData($tableName, $expression);
    // Updating data in a table
    public function UpdateData($tableName, $fields, $expression);
    // Verifying if there is some result of a query
    public function IsExist($tableName, $expression);
    // Selecting a line
    public function GetLine($tableName, $expression, $fields = '*');
    // Selecting a value
    public function GetValue($tableName, $field, $expression);
    // Freeing the result set
    public function FreeResult();
    // Closing connection
    public function __destruct();
}



class DbMysql
{
    // Preferences
    private $host = 'localhost';// Host name
    private $database = 'lane';// Database name
    private $user = 'alex';// User name
    private $password = 'ghjrcb';// Password

    private $connect; // connect handler
    private $query = ''; // query handler
    private $result =''; // result handler
    private $queries_num = 0; // queries counter

###End of header###


    // Connecting to the database, using preference's options
    public function __construct()
    {
        $this->connect = mysql_connect($this->host, $this->user, $this->password) or die('Cannot connect to mysql');
        // selection of the database
        mysql_select_db($this->database, $this->connect) or die('Cannot select database');
    }

    // Set a char set
    public function SetCharset($charset)
    {
        mysql_set_charset($charset, $this->connect) or make_error(mysql_error(), $charset, 'Class DbMysql, function SetCharset', 0);
    }

    // Executing a query
    public function Query($query)
    {
        $this->queries_num++;
        return $this->result = mysql_query($query) or make_error(mysql_error(), $query, 'Class DbMysql, function Query', 1);
    }

    // Query result to array ($column is the id's column name (used as a index fo array))
    public function Query2Array($column = 0)
    {
        if(!$this->result)
            die('Query2Array: result is empty');
        else
        {
            $i = 0;
            while($resorce_array = @mysql_fetch_assoc($this->result))
            {
                $i = ($column) ? $resorce_array[$column] : ($i+1);
                $result_array[$i] = $resorce_array;
            }
            if (!empty($result_array))
                return $result_array;
            else
                return array();
        }
    }

    // Counting result lines
    public function Query2Num()
    {
        if(!$this->result)
            die('Query2Num: result is empty');
        else
            return mysql_num_rows($this->result);
    }

    // Creating table
    public function CreateTable($tableName, $fields)
    {
        if (!mysql_query('SELECT * FROM '.$tableName)) // checking if the table exist
        {
            if (is_array($fields))
            {
                foreach ($fields as $column=>$params)
                    @$query.=','.$column.' '.$params;
                mysql_query('CREATE TABLE '.$tableName.' (id int primary key auto_increment'.$query.')') or make_error(mysql_error(), 'CREATE TABLE '.$tableName.' (id int primary key auto_increment'.$query.')', 'Class DbMysql, function CreateTable', 0);
                $this->queries_num++;
                return $tableName;
            }
            else
                die('Mysql error: you need to define fields to create a table (type array).');
        }
        else
            die('Table '.$tableName.' already exist.');
    }

    // Deleting table
    public function DeleteTable($tableName)
    {
        if (mysql_query('SELECT * FROM '.$tableName)) // checking if the table exist
        {
            mysql_query('DELETE FROM '.$tableName) or die('Cannot clear the table.');
            mysql_query('DROP TABLE '.$tableName) or die('Cannot delete the table.');
        }
        else
            die('Function DeleteTable: table does not exist');
    }

    // Adding a line into a table
    public function AddLine($tableName, $fields)
    {
        if (is_array($fields))
        {
            foreach ($fields as $column=>$value)
            {
                @$columns .= ','.$column;
                @$values .= (is_numeric($value)) ? ','.$value : ',\''.$value.'\'' ;
            }
            mysql_query('INSERT INTO '.$tableName.'('.substr($columns,1).') VALUES('.substr($values,1).')') or make_error(mysql_error(), 'INSERT INTO '.$tableName.'('.substr($columns,1).') VALUES('.substr($values,1).')', 'Class DbMysql, function AddLine', 1);
            $this->queries_num++;
            return 1;
        }
        else
            die('You need to define fields before inserting them');
    }

    // Deleting data from a table
    public function DeleteData($tableName, $expression)
    {
        mysql_query('DELETE FROM '.$tableName.' WHERE '.$expression) or make_error(mysql_error(),'table: '.$tableName.' | expression: '.$expression, 'Class DbMysql, function DeleteData', 0);
        $this->queries_num++;
        return 1;
    }

    // Updating data in a table
    public function UpdateData($tableName, $fields, $expression)
    {
        if (is_array($fields))
        {
            foreach ($fields as $column=>$value)
                @$upd .= ', '.$column.' = '.((is_numeric($value)) ? $value : '\''.$value.'\'');
            mysql_query('UPDATE '.$tableName.' SET '.substr($upd, 1).' WHERE '.$expression) or make_error(mysql_error(), 'UPDATE '.$tableName.' set '.substr($upd, 1).' where '.$expression, 'Class DbMysql, function UpdateData', 1);
            $this->queries_num++;
        }
        else
            die('You need to define the fields before updateting them (array type).');
    }

    // Verifying if there is some result...
    public function IsExist($tableName, $expression)
    {
        $result = mysql_query('SELECT * FROM '.$tableName.' WHERE '.$expression) or make_error(mysql_error(), 'SELECT * FROM '.$tableName.' WHERE '.$expression, 'Class DbMysql, function IsExist', 1);
        $this->queries_num++;
        if (mysql_num_rows($result) == 1)
            return 1;
        elseif (mysql_num_rows($result) > 1)
            die('Class DbMysql, function IsExist: found '.mysql_num_rows($result).' values in place of 0/1');
        else
            return 0;
    }

    // Selecting a line
    public function GetLine($tableName, $expression, $fields = '*')
    {
        $query = mysql_query('SELECT '.$fields.' FROM '.$tableName.' WHERE '.$expression) or make_error(mysql_error(), 'SELECT '.$fields.' FROM '.$tableName.' WHERE '.$expression, 'Class DbMysql, function GetLine', 1);
        $this->queries_num++;
        $result = mysql_fetch_assoc($query);
        if(empty($result))
            return 0;
        if (mysql_num_rows($query) == 1)
            return $result;
        else
            die ('You have >=two same values in GetLine. Something is wrong woth Db... -_-'.'SELECT '.$fields.' FROM '.$tableName.' WHERE '.$expression);
    }

    // Selecting a value
    public function GetValue($tableName, $field, $expression)
    {
        $query = mysql_query('SELECT '.$field.' FROM '.$tableName.' WHERE '.$expression) or make_error(mysql_error(), 'SELECT * FROM '.$tableName.' WHERE '.$expression, 'Class DbMysql, function GetValue', 1);
        $this->queries_num++;
        $result = mysql_fetch_assoc($query);
        if(empty($result))
            return 0;
        if (mysql_num_rows($query) == 1)
            return $result[$field];
        else
            die ('You have two same values in GetLine. Something is wrong woth Db... -_-');
    }

    // Freeing the result set
    public function FreeResult()
    {
        mysql_free_result($this->result) or make_error(mysql_error(), '', 'Class DbMysql, function FreeResult', 1);
        return 1;
    }

    // Closing connection
    public function __destruct()
    {
        mysql_close($this->connect) or make_error(mysql_error(), '', 'Class DbMysql, function FreeResult', 1);
        return 1;
    }
}
?>
